
import {getNewCartGoods, mergeLocalCart, findCartList, insertCart, deleteCart, updateCart, checkAllCart} from '@/api/cart'
export default {
  namespaced: true,
  state () {
    return {
      // 购物车商品内容
      list: []
    }
  },
  //计算属性
  getters: {
    //有效商品列表:库存+isEffective
    validList(state) {
      return state.list.filter(item => item.stock > 0 && item.isEffective)
    },
    //有限商品总价
    validTotal(state, getters) {
      return getters.validList.reduce((p, c) => p + parseInt(c.nowPrice * 100) * c.count, 0)/100
    },
    //有效商品件数
    validCount (state, getters) {
      return getters.validList.reduce((p, c) => p + c.count, 0)
    },

    //已选中商品
    selectGoodsList (state, getters) {
      //从有效商品中筛选
      return getters.validList.filter(item => item.selected)
    },
    //已选中商品数量
    selectGoodsCount(state, getters) {
      return getters.selectGoodsList.reduce((p, c) => p + c.count, 0)
    },
    //已选中商品价格
    selectGoodsTotal (state, getters) {
      return getters.selectGoodsList.reduce((p, c) => p + parseInt(c.nowPrice * 100) * c.count, 0)/100
    },
    //无效商品
    unValidGoods (state) {
      return state.list.filter(item => item.stock <= 0 || !item.isEffective)
    },
    //是否全选
    isAllSelect (state, getters) {
      return getters.validList.length !== 0 && getters.selectGoodsList.length === getters.validList.length
    }

  },
  //准备好存储的字段
  //判断购物车是否有同样商品
  //如有，累加，没有，把商品添加购物车到最前面
  //判断是否登录
  mutations: {
    //设置购物车
    setCart (state, payload) {
      state.list = payload
    },
    
    //加入购物车
    insertCart(state, payload) {
      //查找购物车里是否有相同商品
      const goodsIndex = state.list.findIndex(goods => goods.skuId === payload.skuId)
      if(goodsIndex > -1) {
        //有商品，累加
        //获取商品数量
        const count = state.list[goodsIndex].count
        //累加
        payload.count += count
        //删除原来的
        state.list.splice(goodsIndex, 1)
      } 
      //追加新的
      state.list.unshift(payload)
    },

    //修改购物车
    updateCart (state, goods) {
      //goods  商品信息：nowprice, stock, iseffective
      //goods, 商品对象字段不固定，对象中有哪些字段就改那些字段，字段的值合理才改
      //goods  商品对象 必须有skuID
      const updateGoods = state.list.find(item => item.skuId === goods.skuId)
      // 循环健
      for(const key in goods) {
        if(goods[key] !== undefined && goods[key] !== null && goods[key] !== '') {
          updateGoods[key] = goods[key]
        }
      }
    },

    //删除购物车
    //需拿到点击商品的skuid
    deleteCart (state, payload) {
      //payload为点击商品传入的skuId
      //获取点击商品的索引
      const index = state.list.findIndex(item => item.skuId === payload)
      //执行删除操作
      state.list.splice(index, 1)
    }
  },
  actions: {
    //合并购物车
    async mergeCart (cxt) {
      console.log(cxt.state.list);
      const cartList = cxt.state.list.map(goods => {
        return {skuId: goods.skuId, selected: goods.selected, count: goods.count}
      })
      await mergeLocalCart(cartList)
      //合并成功,清空本地购物车
      cxt.commit('setCart', [])
    },

    //修改sku信息
    updateCartSku (cxt, {oldSkuId, newSku}) {
      return new Promise ((resolve, reject) => {
        if(cxt.rootState.user.profile.token) {
          //已登录
          const oldGoods = cxt.state.list.find(item => item.skuId === oldSkuId)
          deleteCart([oldGoods.skuId]).then(() => {
            return insertCart({skuId: newSku.skuId, count: oldGoods.count})
          }).then(() => {
            return findCartList()
          }).then((data) => {
            cxt.commit('setCart', data.result)
            resolve()
          })

        } else {
          //未登录
          //找出旧商品信息
          //删除旧商品数据
          //合并
          //添加新的商品
          const oldGoods = cxt.state.list.find(item => item.skuId === oldSkuId)
          cxt.commit('deleteCart', oldSkuId)
          const {skuId, price: nowPrice, specsText: attrsText, inventory: stock} = newSku
          const newGoods = {...oldGoods, skuId, nowPrice, attrsText, stock}
          cxt.commit('insertCart', newGoods)
          resolve()
        }
      })

    },

    //批量删除已选中商品
    bathDeleteCart (cxt, isClear) {
      return new Promise ((resolve, reject) => {
        if(cxt.rootState.user.profile.token) {
          //已登录
          // 获取已选中商品的skuid
          const ids = cxt.getters[isClear? 'unValidGoods': 'selectGoodsList'].map(item => item.skuId)
          //调用批量删除接口
          deleteCart(ids).then(() => {
            return findCartList()
          }).then(data => {
            cxt.commit('setCart', data.result)
            resolve()
          })
          
        } else {
          //未登录
          //拿到已选中的商品,循环每一个商品，调用删除函数
          cxt.getters[isClear? 'unValidGoods': 'selectGoodsList'].forEach(item => {
            cxt.commit('deleteCart', item.skuId)
          })
          resolve()
        }
      })
    },
    //判断是否登录，加入购物车
    insertCart (context, payload) {
      console.log(context.state.list);
      //判断有无token
      return new Promise ((resolve, reject) => {
        insertCart(payload).then(() => {
          //加入成功，获取最新列表
          return findCartList()
        }).then(data => {
          context.commit('setCart', data.result)
          resolve()
        })
        //已登录
        if(context.rootState.user.profile.token) {
        } else {
          //未登录
          context.commit('insertCart', payload)
          resolve()
        }
      })
    },
     
    //获取最新商品列表
    findCart (cxt) {
      return new Promise ((resolve, reject) => {
        if(cxt.rootState.user.profile.token) {
          //已登录
          findCartList().then(data => {
            cxt.commit('setCart', data.result)
            resolve()
          })
        } else {
          //未登录
          //同时发送请求，等所有请求成功，一起修改
          //promise.all(promise数组).then((dataList) => {}) 同时发请求，所有请求成功，得到所有成功结果
          const promiseArr = cxt.state.list.map(goods => {
            return getNewCartGoods(goods.skuId)
          })

          Promise.all(promiseArr).then((dataList) => {
            //更新数据
            dataList.forEach((data, i) => {
              cxt.commit('updateCart', {skuId: cxt.state.list[i].skuId, ...data.result})
            })
            //resolve()代表操作成功
            resolve()
          })

        }
      })
    },

    //删除单个购物车商品
    deleteCart (cxt, skuId) {
      return new Promise ((resolve, reject) => {
        //判断是否登录
        if(cxt.rootState.user.profile.token) {
          //已登录
          deleteCart([skuId]).then(() =>{
            //删除成功，重新获取列表
            return findCartList()
          }).then(data => {
            cxt.commit('setCart', data.result)
            resolve()
          })
        } else {
          //未登录
          cxt.commit('deleteCart', skuId)
          resolve()
        }
      })
    },

    //修改购物车（状态，数量）
    updateCart (cxt, payload) {
      return new Promise ((resolve, reject) => {
        //判断是否登录
        if(cxt.rootState.user.profile.token) {
          //已登录
          updateCart(payload).then(() => {
            return findCartList()
          }).then(data => {
            cxt.commit('setCart', data.result)
            resolve()
          })

        } else {
          //未登录
          cxt.commit('updateCart', payload)
          resolve()
        }
      })

    },

    //修改全选状态
    updateAll (cxt, selected) {
      return new Promise ((resolve, reject) => {
        //判断是否登录
        if(cxt.rootState.user.profile.token) {
          //已登录
          const ids = cxt.getters.validList.map(item => item.skuId)
          checkAllCart({selected, ids}).then(() => {
            return findCartList()
          }).then(data => {
            cxt.commit('setCart', data.result)
            resolve()
          })


        } else {
          //未登录
          cxt.getters.validList.forEach(item => {
             // 1. 获取有效的商品列表，遍历的去调用修改mutations即可
            cxt.commit('updateCart', { skuId: item.skuId, selected })
          })
          resolve()
        }
      })

    }

  }
}
